const { DB } = require('./sqlite3');

const TriggerDao = {
    addOne({ script, note }, callback) {
        let stmt = DB.prepare("INSERT INTO trigger_script (script, note , c_time) VALUES ( ? , ? , ? )");
        stmt.run([script, note, Date.now()], (err) => {
            if (err) return console.error(err);
            console.log('Add trigger_script', note);
            typeof callback === "function" && callback();
        });
    },
    altOne({ id, script, note }, callback) {
        let stmt = DB.prepare('UPDATE trigger_script SET script = ? , note = ? WHERE id = ?');
        stmt.run([script, note, id], (err) => {
            if (err) return console.error(err);
            console.log('Alter trigger_script, id ', id);
            typeof callback === "function" && callback();
        });
    },
    getOne(id, callback) {
        DB.get("SELECT id,script,c_time,note FROM trigger_script WHERE id = " + id, (err, row) => {
            if (err) return console.error(err);
            console.log('Get trigger_script, id ', id);
            typeof callback === "function" && callback(row);
        });
    },
    delOne(id, callback) {
        DB.run('DELETE FROM trigger_script WHERE id = ' + id, (rtn, err) => {
            if (err) return console.error(err);
            console.log('Delete trigger_script, id ', id);
            typeof callback === "function" && callback(rtn);
        });
    },
    getList(callback) {
        DB.all("SELECT id,c_time,note FROM trigger_script", (err, rows) => {
            if (err) return console.error(err);
            console.log('List trigger_script , length ', rows.length);
            typeof callback === "function" && callback(rows);
        });
    },
}

module.exports.TriggerDao = TriggerDao;